package com.cn.filter;

import com.cn.annoation.NoLogin;
import com.cn.util.AuthUserContext;
import com.cn.util.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * description: AdminTokenFilter <br>
 * date: 2020/5/15 11:56 <br>
 * author: cn_yaojin <br>
 * version: 1.0 <br>
 */
@Slf4j
public class AdminTokenFilter extends BaseController implements HandlerInterceptor {

    @Autowired
    private UrlsFilterExcludeConfig urlsFilterExcludeConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String url = request.getRequestURI();
        log.info("url:" + url);

        //接口加了放行标识，不进行身份校验
        NoLogin noLogin = method.getAnnotation(NoLogin.class);
        if (noLogin != null) {
            return true;
        }

        //获取登录信息，并将其放到localThread中
        var user = super.getToken();

        AuthUserContext.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthUserContext.clean();
    }

}
